package com.example.springbootdemo.listener;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.example.springbootdemo.dto.UserExcelDTO;
import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.enums.GenderEnum;
import com.example.springbootdemo.mybatisplus.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  用户excel监听类
 * </p>
 *
 * @author yurenwei
 * @since 2023/9/7
 */
@Slf4j
public class UserExcelListener implements ReadListener<UserExcelDTO> {

    /**
     * 每隔10条数据存储数据库，然后清理List,方便内存回收
     *
     */
    private static final int BATCH_COUNT = 10;

    /**
     * 缓存的数据
     */
    private List<UserExcelDTO> cacheList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    private IUserService iUserService;

    public UserExcelListener(IUserService iUserService){
        this.iUserService = iUserService;
    }

    /**
     * 每一条数据解析都会调用
     *
     * @param user
     * @param analysisContext
     */
    @Override
    public void invoke(UserExcelDTO user, AnalysisContext analysisContext) {
        log.info("解析到一条数据user:{}", JSON.toJSONString(user));
        cacheList.add(user);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(cacheList.size()>=BATCH_COUNT){
            // 保存数据
            saveData();
            // 存储完成清理list
            cacheList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据都解析完了才会调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 保存数据
     */
    public void saveData(){
        log.info("一共{}条数据，开始存储数据库！",cacheList.size());
        if(CollectionUtils.isNotEmpty(cacheList)){
            List<User> userList = cacheList.stream().map(item -> new User()
                    .setId(IdUtil.getSnowflakeNextId())
                    .setUserName(item.getUserName())
                    .setPhone(item.getPhone())
                    .setGender("男".equals(item.getGender())? GenderEnum.MALE:GenderEnum.FEMALE)
                    .setAddress(item.getAddress())
                    .setRegisterTime(item.getRegisterTime())
                    .setStatus("启用".equals(item.getStatus())))
                    .collect(Collectors.toList());

            // 批量保存
            iUserService.saveBatch(userList);
        }
        log.info("存储数据库成功！");
    }
}
